package com.odais.AE_Planner;

import java.util.ArrayList;

import org.andengine.engine.camera.Camera;
import org.andengine.engine.camera.hud.HUD;
import org.andengine.entity.sprite.ButtonSprite;
import org.andengine.entity.text.AutoWrap;
import org.andengine.entity.text.Text;
import org.andengine.entity.text.TextOptions;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.font.Font;
import org.andengine.opengl.font.FontFactory;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.util.adt.align.HorizontalAlign;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.MotionEvent;

import com.odais.AE_Handler.EnginePopulation;
import com.odais.DataManagement.DataListener;
import com.odais.DataManagement.DataManager;
import com.odais.Reservation.Reservation;
import com.odais.Reservation.ReservationBox;
import com.odais.Reservation.ReservationEntity;
import com.odais.Reservation.ReservationList;

/**
*
* @author Lionel DECELLE
* @since 4 septembre 2012 - 12:21:53
* 
* RoomManager is able to handle HUD information such as Date, remaining table, etc...
* It will load Tiled Map configuration when requested and manage object lists in the current room.
*
*/


public class RoomManager
{
// ===========================================================
// Constants
// ===========================================================

	public static final int DATE_DIALOG_ID = 1;

	// ===========================================================
// Fields
// ===========================================================
	private Activity mActivity;
	private EnginePopulation mEnginePopulation;
	private SceneContext mSceneContextLeft, mSceneContextRight;
	private Camera mCamera;
	private HUD mHUD;
	private Font mFont;
	private String roomHUDTimestampString;
	private Text roomHUDDate;
	private ButtonSprite roomButtonDate;
	private ITextureRegion roomButtonDateTextureRegion;
	private BitmapTextureAtlas mBitmapTextureAtlas;
	

	private float mRoomPosX, mRoomPosY;

	private ArrayList<Table> tableArrayList;
	
	private DataManager dataManager;
	private ReservationList roomDatedReservationList;

// ===========================================================
// Constructors
// ===========================================================

	public RoomManager(Activity activity, EnginePopulation EnginePopulation,
			SceneContext SceneContextLeft, SceneContext SceneContextRight, Camera camera, HUD HUD) {
		super();
		this.mActivity = activity;
		this.mEnginePopulation = EnginePopulation;
		this.mSceneContextLeft = SceneContextLeft;
		this.mSceneContextRight= SceneContextRight;
		this.mCamera = camera;
		this.mHUD = HUD;
		this.roomHUDTimestampString = new String();
		dataManager = new DataManager(mSceneContextLeft.getContext());
		
		//HUD		
		this.mFont = FontFactory.create(mSceneContextRight.getEngine().getFontManager(), mSceneContextRight.getEngine().getTextureManager(), 256, 256, Typeface.create(Typeface.DEFAULT, Typeface.NORMAL), 20, Color.WHITE);
		this.mFont.load();

		VertexBufferObjectManager vertexBufferObjectManager = mSceneContextRight.getEngine().getVertexBufferObjectManager();
		roomHUDDate = new Text(650, 330, this.mFont, "This will be the current date", new TextOptions(AutoWrap.LETTERS, 500, HorizontalAlign.LEFT), vertexBufferObjectManager);
		
		this.mHUD.attachChild(roomHUDDate);
		
		//HUD date button
		this.mBitmapTextureAtlas = new BitmapTextureAtlas(this.mSceneContextRight.getEngine().getTextureManager(), 64, 64, TextureOptions.BILINEAR);
	    BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
		this.mBitmapTextureAtlas.load();
		roomButtonDateTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, mSceneContextRight.getContext(), "bugdroid.png", 0, 0);
		roomButtonDate = new ButtonSprite(600, 280, roomButtonDateTextureRegion, vertexBufferObjectManager){
            @Override
            public boolean onAreaTouched(TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) {
                     if(pSceneTouchEvent.getAction()==MotionEvent.ACTION_UP){
                    	 //Launch date picker
                    	// Creating dialog
                    	 
                    	 showDatePicker();
                    	 
                    	 LoadReservationRoom(roomHUDTimestampString);
                     }
                     return true;
		}};
    	this.mHUD.registerTouchArea(roomButtonDate);
		this.mHUD.attachChild(roomButtonDate);
		
		
		//Registrate RoomManager as data listener
		DataListener dataListener = new DataListener() {
			@Override
			public void onDataUpdate(ReservationList reservationArrayListUpdated) {

				//Catch confirmed list
				if(reservationArrayListUpdated.getListType().equals(DataManager.UPDATE_TYPE_CONFIRMED_DATED_LIST))
				{	
					roomDatedReservationList = reservationArrayListUpdated;
					RefreshRoom();
				}
			}
		};
		
		DataManager.setOnDataUpdateListener(dataListener);
	}
	
	//Date picker
	public void showDatePicker()
	{
		mActivity.runOnUiThread(new Runnable() {
	        public void run() {
	        	mActivity.showDialog(DATE_DIALOG_ID);
	        }
	    });
	}

	

// ===========================================================
// Getter & Setter
// ===========================================================

	public void setRoomHUDDate(String roomHUDTimestamp) {
		this.roomHUDTimestampString = roomHUDTimestamp;
		this.roomHUDDate.setText(roomHUDTimestampString);
	}

// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
	
	public void LoadTiledRoom()
	{
		tableArrayList = (ArrayList<Table>) mEnginePopulation.getList("Table");
		
		this.mRoomPosX = this.mCamera.getWidth()/4;
		this.mRoomPosY = this.mCamera.getHeight()/4;
		tableArrayList.add(new Table(this.mSceneContextRight, this.mRoomPosX, this.mRoomPosY, 4, true, 0));
		this.mRoomPosX = this.mCamera.getWidth()/4*3;
		this.mRoomPosY = this.mCamera.getHeight()/4;
		tableArrayList.add(new Table(this.mSceneContextRight, this.mRoomPosX, this.mRoomPosY, 6, true, 1));
		this.mRoomPosX = mCamera.getWidth()/4;
		this.mRoomPosY = mCamera.getHeight()/4*3;
		tableArrayList.add(new Table(this.mSceneContextRight, this.mRoomPosX, this.mRoomPosY, 10, true, 2));
		this.mRoomPosX = mCamera.getWidth()/4*3;
		this.mRoomPosY = mCamera.getHeight()/4*3;
		tableArrayList.add(new Table(this.mSceneContextRight, this.mRoomPosX, this.mRoomPosY, 12, true, 3));
	}
	
	public void setItemNumberForItem(Reservation reservation, int itemNumber)
	{
		reservation.setItemNumTable(itemNumber);		
	}
	
	public void setStatus(Reservation reservation, int status)
	{
		reservation.setItemStatus(status);
		
		//Update SQL
		dataManager.updateItem(reservation);
	}
	
	public void LoadReservationRoom(String roomHUDTimestamp)
	{
		setRoomHUDDate(roomHUDTimestamp);
		
		//Call DataManager to get a reservation list at a specific date
		dataManager.GetRoomAt(roomHUDTimestampString);
		
		
	}

	public void RefreshRoom()
	{
		boolean tableFound;
		//Clean all scene children
		for(int i=0; i<mSceneContextRight.getScene().getChildCount(); i++)
		{
			//Make it non visible
			//mReservationBoxList.get(i).setVisible(false, false);
			//Destroy in scene A
			//mReservationBoxList.get(i).killA();
			//Destroy in scene B
			//mReservationBoxList.get(i).killB();
			//Dispose the instantiation
			//mReservationBoxList.get(i).dispose();
			
			//mSceneContext.getScene().getChildByIndex(i).kill();
			
			//TODO check if no side effect by measuring the heap
		}
		mSceneContextRight.getScene().clearChildScene();
		tableArrayList.clear();
		LoadTiledRoom();
		
		//Now we need recurrently load reservations in desired table while verifying if it exists...
		if((roomDatedReservationList!=null) && (roomDatedReservationList.size()>0))
		{
			for(int i=0; i<roomDatedReservationList.size(); i++)
			{
				tableFound = false;
				for(int j=0; j<tableArrayList.size(); j++)
				{
					if(roomDatedReservationList.get(i).getItemNumTable() == tableArrayList.get(j).getItemNumber())
					{
						ReservationEntity reservationEntity = new ReservationEntity(mSceneContextLeft, mSceneContextRight);
						reservationEntity.getReservationBox_RightPanel().setPosition(tableArrayList.get(j).getX(), tableArrayList.get(j).getY());
						reservationEntity.setReservation(roomDatedReservationList.get(i));
						tableArrayList.get(j).setReservation(reservationEntity);
						tableFound = true;
						break;
					}
				}
				if(!tableFound)
				{
					ReservationEntity reservationEntity = new ReservationEntity(mSceneContextLeft, mSceneContextRight);				
				}
			}
		}
		
	}
	
	public void RefreshList()
	{
		dataManager.UpdateReservationList(DataManager.UPDATE_TYPE_PENDING_LIST);
	}


}